package com.libbase.extension

import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import com.libbase.utils.FileUtils
import java.math.BigInteger
import java.security.MessageDigest

val String.md5: String
    get() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16)
        .padStart(32, '0')

val String.nameWithExtension: String?
    get() = FileUtils.instance.getNameWithExtension(this)

val String.nameWithoutExtension: String?
    get() = FileUtils.instance.getNameWithoutExtension(this)

val String.nameExtension: String?
    get() = FileUtils.instance.getNameExtension(this)


fun String.encodeURI(): String {
    return Uri.encode(this, ";/?:@&=+$, #")
}

fun String.encodeURIComponent(): String {
    return Uri.encode(this)
}

fun String.decodeURI(): String {
    return Uri.decode(this)
}

fun String.decodeURIComponent(): String {
    return Uri.decode(this)
}

fun String.addUrlParameters(params: Map<String, String>): String {
    return Uri.parse(this).addUrlParameters(params).toString()
}

fun String.downloadLocation(context: Context, fileName: String?): String? {
    return FileUtils.instance.getDownloadsDir(ContextWrapper(context))?.let { filePath ->
        Uri.Builder()
            .path(filePath).apply {
                fileName?.let { fileName ->
                    appendPath(md5)
                    appendPath(fileName)
                } ?: run {
                    appendPath(if (nameExtension != null) "$md5.$nameExtension" else md5)
                }
            }
            .build()
            .toString()
    }
}
